/*
 *  Copyright (C) 2012 Компания ВИТ. web: http://diasled.ru Е-mail:  vit@diasled.ru
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package ru.apertum.diasled.forms;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import ru.apertum.diasled.model.Patient;

/**
 *
 * Просматриваем и редактируем параметры пациента.
 * @author Evgeniy Egorov, Aperum Projects
 */
public class FPatientEditor extends javax.swing.JDialog {

    public static FPatientEditor getInstance() {
        return NewSingletonHolder.INSTANCE;
    }

    private static class NewSingletonHolder {

        private static final FPatientEditor INSTANCE = new FPatientEditor(null, true);
    }

    /** Creates new form FPatientEditor */
    private FPatientEditor(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        // будет закрывать по esc
        ActionListener escListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        };

        getRootPane().registerKeyboardAction(escListener,
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);
        
        try {
           setIconImage(ImageIO.read(DiasledView.class.getResource("/ru/apertum/diasled/forms/resources/favicon.png")));
        } catch (IOException ex) {
            System.err.println(ex);
        }

    }

    /**
     * Диалог редактирования или создания нового пациента.
     * @param patient пациент для редактирования, может быть null, в этом случае создается новый пациент.
     * @return готовый или отредактированный пациент. Если вернет null, значит был отказ от редактирования.
     */
    static Patient editPatient(Patient patient) {
        getInstance().setPatient(patient);
        getInstance().setLocationRelativeTo(null);
        flag = false;
        getInstance().setVisible(true);
        return flag ? getInstance().getPatient() : null;
    }
    private static boolean flag = false;
    private Patient patient = null;

    public Patient getPatient() {
        return patient;
    }

    public void setPatient(Patient patient) {
        this.patient = patient;
        if (patient == null) {
            textFieldFirstName.setText("");
            textFieldSecondName.setText("");
            textFieldMiddleName.setText("");
            spinnerBirthday.getModel().setValue(new Date());
            textFieldAddress.setText("");
            textFieldPhone.setText("");
            spinnerWeigth.getModel().setValue(70);
            spinnerHeight.getModel().setValue(180);
            comboBoxSex.setSelectedIndex(0);
            textFieldProfession.setText("");
            textAreaPatientComment.setText("");
        } else {
            textFieldFirstName.setText(patient.getFirstName());
            textFieldSecondName.setText(patient.getSecondName());
            textFieldMiddleName.setText(patient.getMiddleName());
            spinnerBirthday.getModel().setValue(patient.getBirthday());
            textFieldAddress.setText(patient.getAddress());
            textFieldPhone.setText(patient.getPhone());
            spinnerWeigth.getModel().setValue(patient.getWeight());
            spinnerHeight.getModel().setValue(patient.getHeight());
            comboBoxSex.setSelectedIndex(patient.getSex() ? 0 : 1);
            textFieldProfession.setText(patient.getProfession());
            textAreaPatientComment.setText(patient.getComments());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelButtons = new javax.swing.JPanel();
        buttonOK = new javax.swing.JButton();
        buttonCancel = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        textFieldSecondName = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        textFieldFirstName = new javax.swing.JTextField();
        textFieldMiddleName = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        textFieldAddress = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        textFieldPhone = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        spinnerWeigth = new javax.swing.JSpinner();
        jLabel7 = new javax.swing.JLabel();
        spinnerHeight = new javax.swing.JSpinner();
        jLabel8 = new javax.swing.JLabel();
        comboBoxSex = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        textFieldProfession = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textAreaPatientComment = new javax.swing.JTextArea();
        spinnerBirthday = new javax.swing.JSpinner();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(ru.apertum.diasled.Diasled.class).getContext().getResourceMap(FPatientEditor.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        panelButtons.setBorder(new javax.swing.border.MatteBorder(null));
        panelButtons.setName("panelButtons"); // NOI18N

        buttonOK.setText(resourceMap.getString("buttonOK.text")); // NOI18N
        buttonOK.setName("buttonOK"); // NOI18N
        buttonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonOKActionPerformed(evt);
            }
        });

        buttonCancel.setText(resourceMap.getString("buttonCancel.text")); // NOI18N
        buttonCancel.setName("buttonCancel"); // NOI18N
        buttonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelButtonsLayout = new javax.swing.GroupLayout(panelButtons);
        panelButtons.setLayout(panelButtonsLayout);
        panelButtonsLayout.setHorizontalGroup(
            panelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelButtonsLayout.createSequentialGroup()
                .addContainerGap(322, Short.MAX_VALUE)
                .addComponent(buttonCancel)
                .addGap(18, 18, 18)
                .addComponent(buttonOK, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        panelButtonsLayout.setVerticalGroup(
            panelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelButtonsLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(panelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonOK)
                    .addComponent(buttonCancel))
                .addContainerGap())
        );

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        textFieldSecondName.setText(resourceMap.getString("textFieldSecondName.text")); // NOI18N
        textFieldSecondName.setName("textFieldSecondName"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        textFieldFirstName.setText(resourceMap.getString("textFieldFirstName.text")); // NOI18N
        textFieldFirstName.setName("textFieldFirstName"); // NOI18N

        textFieldMiddleName.setText(resourceMap.getString("textFieldMiddleName.text")); // NOI18N
        textFieldMiddleName.setName("textFieldMiddleName"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        textFieldAddress.setText(resourceMap.getString("textFieldAddress.text")); // NOI18N
        textFieldAddress.setName("textFieldAddress"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        textFieldPhone.setText(resourceMap.getString("textFieldPhone.text")); // NOI18N
        textFieldPhone.setName("textFieldPhone"); // NOI18N

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        spinnerWeigth.setName("spinnerWeigth"); // NOI18N

        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        spinnerHeight.setName("spinnerHeight"); // NOI18N

        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N

        comboBoxSex.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Мужской", "Женский" }));
        comboBoxSex.setName("comboBoxSex"); // NOI18N

        jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
        jLabel9.setName("jLabel9"); // NOI18N

        textFieldProfession.setText(resourceMap.getString("textFieldProfession.text")); // NOI18N
        textFieldProfession.setName("textFieldProfession"); // NOI18N

        jLabel10.setText(resourceMap.getString("jLabel10.text")); // NOI18N
        jLabel10.setName("jLabel10"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        textAreaPatientComment.setColumns(20);
        textAreaPatientComment.setFont(resourceMap.getFont("textAreaPatientComment.font")); // NOI18N
        textAreaPatientComment.setRows(5);
        textAreaPatientComment.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("textAreaPatientComment.border.title"))); // NOI18N
        textAreaPatientComment.setName("textAreaPatientComment"); // NOI18N
        jScrollPane1.setViewportView(textAreaPatientComment);

        spinnerBirthday.setModel(new javax.swing.SpinnerDateModel());
        spinnerBirthday.setEditor(new javax.swing.JSpinner.DateEditor(spinnerBirthday, "dd.MM.yyyy"));
        spinnerBirthday.setName("spinnerBirthday"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelButtons, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8)
                    .addComponent(jLabel9)
                    .addComponent(jLabel10)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textFieldFirstName, javax.swing.GroupLayout.DEFAULT_SIZE, 351, Short.MAX_VALUE)
                    .addComponent(textFieldMiddleName, javax.swing.GroupLayout.DEFAULT_SIZE, 351, Short.MAX_VALUE)
                    .addComponent(comboBoxSex, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textFieldProfession, javax.swing.GroupLayout.DEFAULT_SIZE, 351, Short.MAX_VALUE)
                    .addComponent(textFieldAddress, javax.swing.GroupLayout.DEFAULT_SIZE, 351, Short.MAX_VALUE)
                    .addComponent(textFieldPhone, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textFieldSecondName, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 351, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(spinnerBirthday, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(spinnerHeight, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(spinnerWeigth, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 53, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textFieldSecondName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textFieldFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textFieldMiddleName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(spinnerBirthday, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textFieldAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textFieldPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(spinnerWeigth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(spinnerHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboBoxSex, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textFieldProfession, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
        setVisible(false);
    }//GEN-LAST:event_buttonCancelActionPerformed

    private void buttonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOKActionPerformed
        // Обязательные поля
        if (textFieldSecondName.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null,
                    "Введите фамилию пациента",
                    "Не полные данные",
                    JOptionPane.NO_OPTION);
            textFieldSecondName.requestFocusInWindow();
            return;
        }
        if (Math.abs(((Date) spinnerBirthday.getModel().getValue()).getTime() - new Date().getTime()) / 1000000 < 93312) {
            JOptionPane.showMessageDialog(null,
                    "Укажите дату рождения пациента",
                    "Не полные данные",
                    JOptionPane.NO_OPTION);
            spinnerBirthday.requestFocusInWindow();
            return;
        }


        if (patient == null) {
            patient = new Patient();
        }
        patient.setFirstName(textFieldFirstName.getText());
        patient.setSecondName(textFieldSecondName.getText());
        patient.setMiddleName(textFieldMiddleName.getText());
        patient.setBirthday((Date) spinnerBirthday.getModel().getValue());
        patient.setAddress(textFieldAddress.getText());
        patient.setPhone(textFieldPhone.getText());
        patient.setWeight((Integer) spinnerWeigth.getModel().getValue());
        patient.setHeight((Integer) spinnerHeight.getModel().getValue());
        patient.setSex(comboBoxSex.getSelectedIndex() == 0 ? true : false);
        patient.setProfession(textFieldProfession.getText());
        patient.setComments(textAreaPatientComment.getText());
        flag = true;
        setVisible(false);
    }//GEN-LAST:event_buttonOKActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCancel;
    private javax.swing.JButton buttonOK;
    private javax.swing.JComboBox comboBoxSex;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel panelButtons;
    private javax.swing.JSpinner spinnerBirthday;
    private javax.swing.JSpinner spinnerHeight;
    private javax.swing.JSpinner spinnerWeigth;
    private javax.swing.JTextArea textAreaPatientComment;
    private javax.swing.JTextField textFieldAddress;
    private javax.swing.JTextField textFieldFirstName;
    private javax.swing.JTextField textFieldMiddleName;
    private javax.swing.JTextField textFieldPhone;
    private javax.swing.JTextField textFieldProfession;
    private javax.swing.JTextField textFieldSecondName;
    // End of variables declaration//GEN-END:variables
}
